import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080/api/v1',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: true
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.debug(`[API Request] ${config.method.toUpperCase()} ${config.url}`, {
      params: config.params,
      data: config.data
    });
    
    if (config.method === 'get' && config.params) {
      config.paramsSerializer = {
        encode: param => encodeURIComponent(param),
        serialize: params => {
          return Object.entries(params)
            .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
            .join('&');
        }
      };
    }
    return config;
  },
  error => {
    console.error('[API Request Error]', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.debug(`[API Response] ${response.config.url}`, {
      status: response.status,
      data: response.data
    });
    return response.data;
  },
  error => {
    const errorInfo = {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message,
      responseData: error.response?.data
    };
    console.error('[API Response Error]', errorInfo);

    let errorMessage = '请求失败';
    if (error.response) {
      switch (error.response.status) {
        case 400: errorMessage = '请求参数错误'; break;
        case 401: errorMessage = '未授权，请登录'; break;
        case 403: errorMessage = '拒绝访问'; break;
        case 404: errorMessage = `请求地址不存在: ${error.config.url}`; break;
        case 500: errorMessage = '服务器内部错误'; break;
        default: errorMessage = `请求失败: ${error.response.status}`;
      }
      if (error.response.data?.message) {
        errorMessage = error.response.data.message;
      }
    } else if (error.request) {
      errorMessage = '服务器无响应';
    }

    return Promise.reject(new Error(errorMessage));
  }
);

export default {
  // 调度相关API
  async getAllDispatches() {
    return api.get('/dispatches');
  },

  async getDispatchByWorkstation(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.get(`/workstations/${cleanWsid}/queue`);
  },

  async startProcessing(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.put(`/dispatches/${cleanWsid}/start`);
  },

  async pauseProcessing(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.put(`/dispatches/${cleanWsid}/pause`);
  },

  async resumeProcessing(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.put(`/dispatches/${cleanWsid}/resume`);
  },

  async finishProcessing(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.put(`/dispatches/${cleanWsid}/finish`);
  },

  async schedulePieces() {
    return api.get('/dispatches/schedule');
  },

  async getWorkstationStatus(wsid) {
    const cleanWsid = String(wsid).trim();
    return api.get(`/workstations/${cleanWsid}/status`);
  },

  // 生成工件API
  async generatePieces(pplansheet) {
    return api.post(`/pieces/generate/${pplansheet}`);
  },

  // 辅助方法
  setHeader(key, value) {
    api.defaults.headers.common[key] = value;
  },

  removeHeader(key) {
    delete api.defaults.headers.common[key];
  }
};